package com.rndemo.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Parcel;

import com.rndemo.annotations.FieldTag;
import com.rndemo.annotations.FieldType;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tzj on 2018/5/21.
 */
public class BaseDB extends BaseReflex implements ISqlite {
    @FieldTag(type = FieldType.ignore)
    protected static final HashMap<Class,SQLiteDelegate> map = new HashMap<>();

    protected Date _id = new Date();//必定有一个_id

    public BaseDB(){
        if(getDbHelper()==null){
            map.put(getClass(),new SQLiteDelegate(this));
        }
    }
    public BaseDB(Object obj){
        //让子类 先new 后 new SQLiteDelegate
    }
    public long insert(String where, Object... data) {
        return insert(null,where,data);
    }
    /**
     * 增
     * 有所给条件的内容的话改为update
     * @param where 为NULL时表明不管有没有直接插入
     * 				为""时表明查看有无完全一样的没有再插入
     */
    public long insert(ContentValues values,String where,Object... strs){
        if(values==null){
            values = contentValues();
        }
        if(values.size()<=0){
            return 0;
        }
        return getDbHelper().getWritableDatabase().insert(dbName(),null,values);
    }
    /**
     * 删
     * @param where 为NULL时删除_id
     * @param data
     * @return: void
     */
    public int delete(String where,String... data){
        return getDbHelper().getWritableDatabase().delete(dbName(),where,data);
    }
    public Where where(String where, String... data){
        return new Where(this,where,data);
    }
    /**
     * 查
     * @param where 为NULL时有没有与本类完全一样的内容
     */
    public List select(String where, String... data){
        String sql = null;
        if(where == null){
            sql = "select * from " + dbName();
        }else {
            sql = "select * from " + dbName() + " where " + where;
        }
        List ret = new ArrayList<>();
        Cursor cursor = getDbHelper().getReadableDatabase().rawQuery(sql, data);
        if (cursor == null) {
            return ret;
        }
        while (cursor.moveToNext()) {
            try {
                BaseDB baseDB = getClass().newInstance();
                filling(baseDB,getClass(),cursor);
                ret.add(baseDB);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        cursor.close();
        return ret;
    }
    public int update(String where, String... data) {
        return update(null,where,data);
    }
    /**
     * 改
     * @param where 不能为空
     */
    public int update(ContentValues values,String where, String... data) {
        if(values==null){
            values = contentValues();
        }
        if(values.size()<=0){
            return 0;
        }
        return getDbHelper().getWritableDatabase().update(dbName(),values,where,data);
    }
    protected ContentValues contentValues(){
        Map<String, Object> map = toValue(getClass(), new HashMap<String, Object>());
        Parcel obtain = Parcel.obtain();
        obtain.writeMap(map);
        obtain.setDataPosition(0);
        ContentValues values = ContentValues.CREATOR.createFromParcel(obtain);
        obtain.recycle();
        return values;
    }

    public SQLiteDelegate getDbHelper() {
        return map.get(getClass());
    }

    //=======================================================
    @Override
    public void initFields() {
        if(objFiles.size()==0){
            toDb(getClass());
        }
    }
    @Override
    public int version() {
        return 1;
    }

    @Override
    public String dbName() {
        return getClass().getSimpleName();
    }

    @Override
    public String dbPath() {
        return dbName();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
//        map.put("_id","BIGINT primary key"/*+" autoincrement"*/);
        String tab = createSql(dbName(), objFiles);
        db.execSQL(tab);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    @Override
    public void close() {
        if(getDbHelper()!=null){
            getDbHelper().close();
            map.remove(getClass());
        }
    }

    protected String createSql(String tableName, Map<String, String> column) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("create table ")
                .append(tableName)
                .append("(");
        for (Map.Entry<String, String> entry : column.entrySet()) {
            buffer.append(entry.getKey()).append(" ").append(entry.getValue()).append(",");
        }
        buffer.deleteCharAt(buffer.length() - 1);
        buffer.append(")");
        return buffer.toString();
    }

}
